package sound;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
import javax.sound.sampled.*;
 
public class JLayerPlayer {
	
	public static void main(String[] args) throws FileNotFoundException {
		for (String arg : args) {
			process(new File(arg));
		}
	}
	private static void process(File file) throws FileNotFoundException {
		if (file.isDirectory()) {
			for (File child : file.listFiles()) {
				process(child);
			}
		} else {
			if (file.isFile() && file.getName().toLowerCase().endsWith(".mp3")) {
				playMp3(file);
			}
		}
	}
	public static void playMp3(File file) throws FileNotFoundException {
		FileInputStream is = new FileInputStream(file);
		playMp3(is);
	}
	public static void playMp3(InputStream is) {
		AudioInputStream din = null;
		try {
			AudioInputStream in = AudioSystem.getAudioInputStream(is);
			AudioFormat baseFormat = in.getFormat();
			AudioFormat decodedFormat = new AudioFormat(
					AudioFormat.Encoding.PCM_SIGNED,
					baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
					baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
					false);
			din = AudioSystem.getAudioInputStream(decodedFormat, in);
			DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
			SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
			if(line != null) {
				line.open(decodedFormat);
				byte[] data = new byte[4096];
				// Start
				line.start();
				
				int nBytesRead;
				while ((nBytesRead = din.read(data, 0, data.length)) != -1) {	
					line.write(data, 0, nBytesRead);
				}
				// Stop
				line.drain();
				line.stop();
				line.close();
				din.close();
			}
			
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			if(din != null) {
				try { din.close(); } catch(IOException e) { }
			}
		}
	}
 
}
